import 'dart:async';

import 'package:aihu_getx_app/app/modules/commons/commons.dart';
import 'package:aihu_getx_app/app/modules/commons/model/client_base_config_model.dart';
import 'package:aihu_getx_app/providers/http_provider.dart';
import 'package:aihu_getx_app/utils/constants.dart';
import 'package:carousel_slider/carousel_controller.dart';
import 'package:flutter/foundation.dart';
import 'package:get/get.dart';

class SplashController extends GetxController {
  final count = 30.obs;
  final current = 0.obs;
  final CarouselSliderController carouselController = CarouselSliderController();
  late Timer timer = Timer.periodic(const Duration(seconds: 1), (timer) {});

  @override
  void onInit() {
    if (kDebugMode) {
      print("SplashController.onInit");
    }
    super.onInit();
  }

  @override
  void onReady() {
    if (kDebugMode) {
      print("SplashController.onReady");
    }
    super.onReady();
    carouselController.jumpToPage(Commons.getLastSplashPageIndex());
    reset();
  }

  @override
  void onClose() {
    if (kDebugMode) {
      print("SplashController.onClose");
    }
    super.onClose();
    if (timer.isActive) {
      timer.cancel();
    }
  }

  void increment() => count.value++;

  void decrement() => count.value--;

  void reset({int? offset}) {
    if (null != offset) {
      offset > 0
          ? carouselController.nextPage()
          : carouselController.previousPage();
    }
    count.value = 30;
    if (timer.isActive) {
      timer.cancel();
    }
    timer = Timer.periodic(const Duration(seconds: 1), (timer) {
      if (count.value <= 0) {
        timer.cancel();
        switchPage(null);
        return;
      }
      decrement();
    });
  }

  void switchPage(ClientBaseConfigModel? item) {
    if (kDebugMode) {
      print("switchPage -- item: $item");
    }
    if (item != null) {
      carouselController
          .jumpToPage(Constants.clientBaseConfigData.indexOf(item));
    }
    Commons.setLastSplashPageIndex(current.value)?.then(
      (value) {
        Http.refreshHeaderToken();
        Get.offAllNamed(
            Constants.clientBaseConfigData[current.value].indexPage);
      },
    );
    if (timer.isActive) {
      timer.cancel();
    }
  }
}
